package freespiritsocial.io.user.util

import freespiritsocial.io.user.R
import freespiritsocial.io.user.base.App
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.ticker
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.callback.databind.StringObservableField

class CountDownTimerHelper(private val scope: CoroutineScope,val text: StringObservableField) {
    private val ticker by lazy (LazyThreadSafetyMode.NONE) {
        ticker(1_000L,0)
    }

    fun startCountDown() {
        scope.launch(Dispatchers.IO) {
            repeat(61) {
                val time = 60 - it
                text.set(if (time <= 0) App.instance.getString(R.string.code_get) else "${time}s")
                ticker.receive()
            }
        }
    }

    fun cancel() {
        ticker.cancel()
        text.set(App.instance.getString(R.string.code_get))
    }
}